﻿using NJabber.Client;
using NJabber.Stream.Elements;

namespace NJabber.Client.StanzaFactories
{
    public class RosterStanzaFactory : StanzaFactory<StanzaParameters>, IRosterStanzaFactory
    {
        public Stanza CreateRosterRequest(JID senderId)
        {
            return CreateBasicRosterRequest(IqStanzaTypes.Get, senderId);
        }

        public Stanza CreateAddRosterItemRequest(RosterItem item, JID senderId)
        {
            return CreateUpdateRosterRequest(IqStanzaTypes.Set, senderId, item);
        }

        public Stanza CreateUpdateRosterItemRequest(RosterItem oldValue, RosterItem newValue, JID senderId)
        {
            return CreateUpdateRosterRequest(IqStanzaTypes.Set, senderId, newValue);
        }

        public Stanza CreateDeleteRosterItemRequest(RosterItem item, JID senderId)
        {
            return CreateUpdateRosterRequest(IqStanzaTypes.Set, senderId, item, "remove");
        }

        private IqStanza CreateUpdateRosterRequest(string type, JID senderId, RosterItem item = null, string subscription = "")
        {
            IqStanza stanza = CreateBasicRosterRequest(type, senderId);
            if (item != null) stanza.GetQueryElement().AddContentItem(new RosterItemElement(item.Name, item.Jid, subscription));
            return stanza;
        }

        private IqStanza CreateBasicRosterRequest(string stanzaType, JID senderId)
        {
            IqStanza stanza = CreateStanza<IqStanza>();
            stanza.Type = stanzaType;
            stanza.From = senderId;
            stanza.AddQueryElement(XmppNamespaces.Roster);
            return stanza;
        }
    }
}
